package codeine;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import org.apache.log4j.Logger;

import codeine.configuration.directory.PeerStatusJson;
import codeine.executer.Task;
import codeine.jsons.project_status.PeersProjectsStatus;
import codeine.jsons.project_status.ProjectStatusList;
import codeine.model.Constants;
import codeine.utils.ExceptionUtils;
import codeine.utils.HttpUtils;

import com.google.common.collect.Maps;
import com.google.gson.Gson;

public class UpdaterThreadV2 implements Task
{
	private static final Logger log = Logger.getLogger(UpdaterThreadV2.class);
	public static final long SLEEP_TIME = TimeUnit.SECONDS.toMillis(5);
	@Inject private PeersProjectsStatus peersProjectsStatus;
	@Inject private PeersListRegistry peersListRegistry;
	@Inject private Gson gson;

	@Override
	public void run() {
		Map<String, ProjectStatusList> newMap = Maps.newHashMap();
		for (PeerStatusJson peerStatus : peersListRegistry.peers().values()) {
			String address = peerStatus.host() + ":" + peerStatus.port();
			try {
				ProjectStatusList fetchStatus = fetchStatus(address);
				newMap.put(address, fetchStatus);
			} catch (Exception e) {
				log.warn("failed to get update from peer " + address + "caused by " + ExceptionUtils.getRootCause(e).getMessage());
				log.debug("details of error", e);
			}
		}
		peersProjectsStatus.replaceMap(newMap);
	}

	private ProjectStatusList fetchStatus(String address) {
		String url = "http://" + address + Constants.PROJECT_STATUS_CONTEXT;
		String json = HttpUtils.doGET(url);
		return gson.fromJson(json, ProjectStatusList.class);
	}

}
